// if (!Promise) {
//     setPromise()
// }

// var setPromise = () => {
window.MyPromise = function (func) {//接收一个回调来传入成功和失败的方法
    this.status = 'pend';//
    this.resval = '';
    this.rejval = '';//
    this.rescb = [];
    this.rejcb = [];
    var self = this
    this.resolve = function (res) {
        if (self.status === 'pend') {
            self.status = 'full';
            self.resval = res;
            self.rescb.forEach((ele) => {
                ele()
            })
        }
    }
    this.reject = function (rej) {
        if (self.status === 'pend') {
            self.status = 'fail';
            self.rejval = rej;
            self.rejcb.forEach((ele) => {
                ele()
            })
        }
    }
    try {
        func(this.resolve, this.reject)
    } catch (e) {
        this.reject(e)
    }
}
window.MyPromise.prototype.then = function (func1, func2) {
    var fn1 = func1;
    var fn2 = func2
    if (!fn1) {
        fn1 = function (val) {
            return val
        }
    }
    if (!fn2) {
        fn2 = function (rej) {
            throw new Error(rej)
        }
    }
    var self = this;
    var nextPromise = new MyPromise(function (res, rej) {
        function getfull(res, rej, fn1) {
            return setTimeout(() => {
                try {
                    var nextresolve = fn1(self.resval)
                    if (nextresolve instanceof window.MyPromise) {
                        nextresolve.then(function (val) {
                            res(val)
                        }, function (err) {
                            rej(err)
                        })
                    } else {
                        res(nextresolve)
                    }
                } catch (e) {
                    rej(e)
                }
            })
        }
        function getfail(res, rej, fn2) {
            return setTimeout(() => {
                try {
                    var nextreject = fn2(self.rejval)
                    if (nextreject instanceof window.MyPromise) {
                        nextreject.then(function (val) {
                            res(val)
                        }, function (err) {
                            rej(err)
                        })
                    } else {
                        res(nextreject)
                    }
                } catch (e) {
                    rej(e)
                }
            })
        }
        if (self.status === 'full') {
            getfull(res, rej, fn1)
        }
        if (self.status === 'fail') {
            getfail(res, rej, fn2)
        }
        if (self.status === 'pend') {
            self.rescb.push(function () {
                this.fn = getfull
                this.fn(res, rej, fn1)
            })
            self.rejcb.push(function () {
                this.fn = getfail
                this.fn(res, rej, fn2)
            })
        }
    })
    return nextPromise
}
// }